from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from functools import wraps
from .models import Examinee

def examinee_required(view_func):
    """考生身份验证装饰器（基于session）

    要求用户已登录，并且在session中有考生ID
    """
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        examinee_id = request.session.get('examinee_id')
        if not examinee_id:
            messages.warning(request, '请先登录')
            return redirect('exam_system:login')

        try:
            # 从数据库获取考生信息并添加到request对象中
            request.examinee = Examinee.objects.get(id=examinee_id)
            return view_func(request, *args, **kwargs)
        except Examinee.DoesNotExist:
            messages.error(request, '考生信息无效')
            # 清除无效的session
            request.session.flush()
            return redirect('exam_system:login')

    return wrapper